package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
@Slf4j
@Service
public class ApUnlikesBehaviorServiceImpl implements ApUnlikesBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
        //1.校验参数：判断从线程中获取的用户信息是否为空
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请登录您的账号");
        }
        //2.查询行为实体：判断行为实体是否为空
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "为查询到该实体行为");
        }
        //3.查询不喜欢行为是否存在
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        ApUnlikesBehavior unlikesBehavior = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        if (unlikesBehavior != null && dto.getType().intValue() == 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复此操作");
        }
        //3.1若不存在添加该行为
        if (dto.getType().intValue() == 0) {
            unlikesBehavior = new ApUnlikesBehavior();
            unlikesBehavior.setArticleId(dto.getArticleId());
            unlikesBehavior.setCreatedTime(new Date());
            unlikesBehavior.setEntryId(apBehaviorEntry.getId());
            unlikesBehavior.setType((short) 0);
            mongoTemplate.save(unlikesBehavior);
        } else {
            //取消不喜欢
            mongoTemplate.remove(query, ApUnlikesBehavior.class);
        }
        return ResponseResult.okResult();
    }
}
